package com.jzcn.admin.aop;


import com.alibaba.fastjson.JSON;
import com.jzcn.admin.annotation.ServerLog;
import com.jzcn.common.utils.IpUtil;
import com.jzcn.domain.SysLog;
import com.jzcn.domain.SysUser;
import com.jzcn.service.SysLogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;

/**
 * 系统日志，切面处理类
 *
 * @author Mark sunlightcs@gmail.com
 */
@Aspect
@Component
public class ServerLogAspect {
    @Autowired
    private SysLogService sysLogService;

    @Pointcut("@annotation(com.jzcn.admin.annotation.ServerLog)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        saveSysLog(point, time);
        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) throws Throwable {
        SysLog sysLog = new SysLog();
        //获取request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        if (method != null){
            ServerLog serverLog = method.getAnnotation(ServerLog.class);
            Object[] args = joinPoint.getArgs();
            String params = JSON.toJSONString(args[0]);
            sysLog.setContent(params);
            //注解上的描述
            sysLog.setOperation(serverLog.value());
            sysLog.setCode(serverLog.code());
        }

        // Object result = joinPoint.proceed();

        //设置IP地址
        sysLog.setIp(IpUtil.getIp(request));
        sysLog.setMethod(request.getMethod());
        sysLog.setUrl(request.getRequestURI());
        //用户名
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        if(Objects.nonNull(sysUser)){
            sysLog.setUserId(sysUser.getId());
            sysLog.setCreateTime(new Date());
        }
        //保存系统日志
        sysLogService.save(sysLog);
    }
}
